<?php

/*
 * Camelot PHP Tools
 *
 * @version 2.0
 * @author Bendsoft
 * @package PHP Tools
 * @subpackage Camelot
 * @license FreeBSD License (www.bendsoft.com/licensing/)
 *
 */

/**
 * Builds a document tree from a SharePointDocumentLibrary class instance
 * 
 * @author Bendsoft
 */
class DocumentTree {

    public $DocumentTreeObject;
    private $_treeArray;
    private $_parentId;
    private $_recurisveObject;

    public function __construct($SharePointDocumentLibrary, $ParentId = 0) {

        $this->_treeArray = $SharePointDocumentLibrary;
        $this->_parentId = $ParentId;

        $this->DocumentTreeObject = new ArrayObject();
    }

    public function buildtree($args = null) {

        if (!isset($this->_treeArray->CamelotDocumentLibraryObject))
            return;


        $documents = (array) $this->_treeArray->CamelotDocumentLibraryObject;
        //pr($documents);
        $parentRows = array_filter($documents, array($this, 'filterByParentId'));
        $this->buildRecursiveTree($parentRows, $args);
    }

    private function buildRecursiveTree($parentRows, $args = null) {
        foreach ($parentRows as $row) {

            $urlPrefix = (isset ($args['urlPrefix'])) ? $args['urlPrefix'] : null;
            $urlSuffix = (isset ($args['urlSuffix'])) ? $args['urlSuffix'] : null;
            
            $this->DocumentTreeObject->append(new DocumentTreeObject($row->ID, $row->ParentID, $row->BaseName, $row->ContentType, $row->GUID, $row->Modified, $row->FileSize, $row->FileType, $row->LinkFilename, $row->FolderPath, $urlPrefix, $urlSuffix));

            // Enable this if you want recursive trees
            //$this->_parentId = $row->ID;
            //$childRows = array_filter($this->_treeArray, array($this, 'filterByParentId'));
            //if (count($childRows) > 0) {
            //    $this->buildRecursiveTree($childRows);
            //}
        }
        unset($this->_treeArray);
    }

    private function filterByParentId($documents) {
        return ($documents->ParentID == $this->_parentId);
    }

//    public function append(DocumentTreeObject $value) {
//        parent::append($value);
//    }

    public function __destruct() {
        unset($this);
    }

}

?>
